/// <reference path="../node_modules/chrome-extension-async/chrome-extension-async.d.ts" />
import 'chrome-extension-async'

import { MDCSlider } from '@material/slider'

import { isNull, getActiveTabVolumeFromStorage, getActiveTabVolume, setActiveTabVolume } from './functions'

const sliderElem: HTMLDivElement = document.querySelector('#volume-slider')
const slider = new MDCSlider(sliderElem)
const volumeSpecifyBtn: NodeListOf<HTMLDivElement> = document.querySelectorAll('.volume-specify-btn')

void (async () => {
  // Hide the slider until we know the initial volume
  sliderElem.style.opacity = '0'

  let volumeValue = await getActiveTabVolumeFromStorage()
  console.log('getActiveTabVolumeFromStorage', volumeValue)
  if(isNull(volumeValue)) {
    volumeValue = await getActiveTabVolume()
    console.log('getActiveTabVolume', volumeValue)
  }

  slider.value = volumeValue * 100
  setActiveTabVolume(volumeValue)
  sliderElem.style.opacity = '1'
}) ()

slider.listen('MDCSlider:input', () => {
  const value = slider.value / 100
  setActiveTabVolume(value)
})

volumeSpecifyBtn.forEach(eachBtn => {
  eachBtn.addEventListener('click', (event) => {
    const thisVolume = parseInt(eachBtn.textContent.trim())
    setActiveTabVolume(thisVolume / 100)
    slider.value = thisVolume
  });
});
